<template>
  <div ref="drawerContainer" class="drawer-container" :style="'height:' + contentHeight + 'px'">
    <div ref="miniMap" class="drawer-map"></div>
    <div class="drawer-menu">
      <div v-if="drawerType === 'grid'">
        <div class="drawer-title">画布背景设置</div>
        <div class="drawer-wrap">
          <el-form label-position="left" label-width="90px">
            <el-form-item label="是否显示网格">
              <el-switch v-model="grid.showGrid"></el-switch>
            </el-form-item>
            <div v-show="grid.showGrid">
              <el-form-item label="网格类型">
                <el-radio-group v-model="grid.type" @change="changeGridType">
                  <el-radio v-for="item in gridTypeList" :label="item.value" :key="item.value">
                    <span>{{item.label}}</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="网格大小">
                <el-slider v-model="grid.size" :min="0" :max="30" @change="changeGrid"></el-slider>
              </el-form-item>
              <el-form-item label="网格颜色">
                <el-color-picker :size="itemsize" v-model="grid.args.color" @change="changeGrid" />
              </el-form-item>
              <el-form-item label="网格线宽度">
                <el-slider v-model="grid.args.thickness" :min="0" :max="20" @change="changeGrid"></el-slider>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
      <div v-else-if="drawerType === 'node'">
        <div class="drawer-title">节点设置</div>
        <div class="drawer-wrap">
          <el-form label-position="left" label-width="90px">
            <el-form-item label="节点名称">
              <el-input :size="itemsize" v-model="drawerNode.nodeText" @change="changeNodeText" :disabled="disabled || drawerNode.nodeType === 'Start' || drawerNode.nodeType === 'End'"></el-input>
            </el-form-item>
            <!-- <el-form-item label="节点背景">
              <el-color-picker :size="itemsize" v-model="drawerNode.fill" @change="changeFill" />
            </el-form-item>
            <el-form-item label="字体大小">
              <el-slider v-model="drawerNode.fontSize" :min="10" :max="20" @change="changefontSize"></el-slider>
            </el-form-item>
            <el-form-item label="字体颜色">
              <el-color-picker :size="itemsize" v-model="drawerNode.fontFill" @change="changeFontFill" />
            </el-form-item>
            <el-form-item label="边框宽度">
              <el-slider :size="itemsize" v-model="drawerNode.strokeWidth" :min="0" :max="10" @change="changeStrokeWidth"></el-slider>
            </el-form-item>
            <el-form-item label="边框颜色">
              <el-color-picker :size="itemsize" v-model="drawerNode.stroke" @change="changeStroke" />
            </el-form-item> -->
            <!-- 循环节点 -->
            <el-form-item label="循环实体" v-show="drawerNode.nodeType === 'Circle'">
              <el-select v-model="drawerNode.entityId" :size="itemsize" :disabled="disabled" filterable clearable placeholder="实体" @change="changeFlowNode($event, 'entityId')">
                <el-option v-for="item in curEntityList" :key="item.entityId" :label="item.label" :value="item.entityId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="实体属性" v-show="'Circle'.indexOf(drawerNode.nodeType) > -1">
              <el-select v-model="drawerNode.itemId" :size="itemsize" :disabled="disabled" filterable clearable placeholder="实体属性" @change="changeFlowNode($event, 'itemId')">
                <el-option v-for="item in entityItemInfos" :key="item.itemId" :label="item.label" :value="item.itemId">
                </el-option>
              </el-select>
            </el-form-item>
            <!-- 编辑条件 -->
            <el-form-item label="条件" v-show="drawerNode.nodeType === 'polygon'">
              <el-button :size="itemsize" type="primary" icon="el-icon-edit" @click="showConditionEdit" v-show="selectCellNum == 1">编辑条件</el-button>
            </el-form-item>
            <!-- 任务节点 -->
            <el-form-item label="节点类型" v-show="drawerNode.nodeType === 'Rect'">
              <el-select v-model="drawerNode.flowNodeType" :size="itemsize" :disabled="disabled" filterable placeholder="请选择" @change="changeFlowNode($event, 'flowNodeType')">
                <el-option v-for="(item, index) in flowTypes" :key="index" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="执行规则组" v-show="drawerNode.nodeType === 'Rect' && drawerNode.flowNodeType === '2'">
              <el-select v-model="drawerNode.groupIdentify" :size="itemsize" :disabled="disabled" filterable clearable placeholder="执行规则组" @change="changeFlowNode($event, 'groupIdentify')">
                <el-option v-for="item in groupList" :key="item.groupIdentify" :label="item.groupName" :value="item.groupIdentify">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="子流程" v-show="drawerNode.nodeType === 'Rect' && drawerNode.flowNodeType === '6'">
              <el-select v-model="drawerNode.childFlowIdentify" :size="itemsize" :disabled="disabled" filterable clearable placeholder="子流程" @change="changeFlowNode($event, 'childFlowIdentify')">
                <el-option v-for="item in flows" :key="item.flowIdentify" :label="item.flowName" :value="item.flowIdentify">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="方法" v-show="drawerNode.nodeType === 'Rect' && drawerNode.flowNodeType === '7'">
              <el-select v-model="drawerNode.methodName" :size="itemsize" :disabled="disabled" filterable clearable placeholder="请选择方法" @change="changeFlowNode($event, 'methodName')">
                <el-option v-for="item in codeMethods" :key="item.name" :label="item.className" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
            <!-- 条件为方法，输入方法参数值-->
            <div v-if="drawerNode.flowNodeType === '7' && showParams">
              <div v-for="(p, index) in methodParams" :key="index">
                <el-form-item :size="itemsize" :label="p.desc">
                  <el-input v-model="p.className" :disabled="disabled" placeholder="请输入内容"></el-input>
                </el-form-item>
              </div>
            </div>
            <el-form-item label="" v-if="drawerNode.nodeType === 'Rect' && drawerNode.flowNodeType === '7' && showParams">
              <el-button :size="itemsize" :disabled="disabled" type="primary" @click="checkMethodForm">保存参数</el-button>
            </el-form-item>
            <!-- <el-form-item label="功能">
              <el-button :size="itemsize" type="primary" icon="el-icon-upload2" @click="toTopZIndex" v-show="selectCellNum == 1">置顶</el-button>
              <el-button :size="itemsize" type="error" icon="el-icon-delete" class="margin-left-10" @click="deleteNode" v-show="selectCellNum == 1">删除</el-button>
            </el-form-item> -->
          </el-form>
        </div>
      </div>
      <div v-else-if="drawerType === 'edge'">
        <div class="drawer-title">线条设置</div>
        <div class="drawer-wrap">
          <el-form label-position="left" label-width="80px">
            <el-form-item label="线条文本">
              <el-input :size="itemsize" v-model="drawerEdge.edgeText" @change="changeEdgeText" :disabled="disabled || drawerEdge.isCondition"></el-input>
            </el-form-item>
            <el-form-item label="条件判断" v-if="drawerEdge.isCondition">
              <el-radio-group v-model="drawerEdge.edgeSelect" :disabled="disabled" @change="changeEdgeText">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- <el-form-item label="线条宽度">
              <el-slider v-model="drawerEdge.edgeWidth" :min="1" :max="10" @change="changeEdgeWidth"></el-slider>
            </el-form-item>
            <el-form-item label="线条颜色">
              <el-color-picker :size="itemsize" v-model="drawerEdge.edgeColor" @change="changeEdgeColor" />
            </el-form-item> -->
            <!-- <el-form-item label="功能">
              <el-button :size="itemsize" type="primary" icon="el-icon-upload2" @click="toTopZIndex">置顶</el-button>
              <el-button :size="itemsize" type="error" icon="el-icon-delete" class="margin-left-10" @click="deleteNode">删除</el-button>
            </el-form-item> -->
          </el-form>
        </div>
      </div>
    </div>
    <!-- 收起展开 -->
    <div class="drawer-unfold" @click="toggleDrawer">
      <i class="el-icon-d-arrow-left" v-show="drawerHide"></i>
      <i class="el-icon-d-arrow-right" v-show="!drawerHide"></i>
    </div>
    <el-dialog title="编辑条件" :visible.sync="dialogVisible" width="90%" append-to-body>
      <ConditionEdit ref="conditionEdit" :disabled="disabled" :size="itemsize" :conditionTypes="conditionTypes" :curEntityList="curEntityList"></ConditionEdit>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="disabled" @click="dialogVisible = false">关闭</el-button>
        <template v-else>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveflowJudges">确 定</el-button>
        </template>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CONSTANT from '@/api/constant';
import ConditionEdit from './condition-edit';
import { entityItemList } from '@/api/baseConfig/entity';
import { listGroupInfosByEntity } from '@/api/ruleConfig/groupInfo';
import { listFlowInfosByEntity, getMethodName } from '@/api/ruleConfig/flow';
export default {
  name: 'RightDrawer',
  props: {
    drawerType: {
      type: String,
      default: 'grid'
    },
    selectCell: {
      type: String | Object
    },
    graph: {
      type: String | Object
    },
    grid: {
      type: Object
    },
    itemsize: {
      type: String,
      default: ''
    },
    selectCellNum: {
      type: Number,
      default: 0
    },
    contentHeight: {
      type: Number,
      default: 100
    },
    //循环实体
    curEntityList: {
      type: Array,
      default: () => []
    },
    checkEntity: Array,
    disabled: {
      typeof: Boolean,
      default: false
    }
  },
  data() {
    return {
      gridTypeList: [
        {
          label: '四边',
          value: 'mesh'
        },
        {
          label: '点状',
          value: 'dot'
        }
      ],
      drawerHide: false,
      showParams: false,
      methodParams: [],
      drawerNode: {
        fill: '',
        nodeText: '',
        fontSize: null,
        fontFill: '',
        strokeWidth: null,
        stroke: '',
        //其它参数
        nodeType: '',
        entityId: '',
        itemId: '',
        flowNodeType: '',
        groupIdentify: '',
        childFlowIdentify: '',
        methodName: '',
        methodParams: '',
        methodType: '',
        hasMethodParams: false,
        methodExp: '',
        flowJudges: [],
        // isJudgeNode: '0'
      },
      drawerEdge: {
        isCondition: false,
        edgeText: '',
        edgeSelect: true,
        edgeWidth: null,
        edgeColor: ''
      },
      //循环节点的实体属性
      entityItemInfos: [],
      //条件类型
      conditionTypes: [],
      //任务节点
      // flowTypes: CONSTANT.ruleConfig.flowTypes,
      //执行规则组
      groupList: [],
      //子流程
      flows: [],
      //方法
      codeMethods: [],
      dialogVisible: false
    };
  },
  components: {
    ConditionEdit
  },
  created() {

  },
  mounted() {
  },
  computed: {
    // 任务节点
    flowTypes() {
      return CONSTANT.ruleConfig.flowTypes.filter(item => {
        //移除循环节点和条件节点
        return item.value != '3' && item.value != '5';
      })
    }
  },
  watch: {
    'grid.showGrid'(val) {
      this.$nextTick(() => {
        this.changeGridStatus();
      });
    },
    checkEntity(val) {
      // 关联模型发生改变需重新请求数据
      this.init();
    },
    selectCell: {
      handler(val) {
        if (val) {
          if (val.isNode()) { //节点
            this.drawerNode.fill = val.store.data.attrs.body.fill;
            this.drawerNode.nodeText = val.store.data.attrs.label.text;
            this.drawerNode.fontFill = val.store.data.attrs.label.fill;
            this.drawerNode.fontSize = Number(val.store.data.attrs.label.fontSize);
            this.drawerNode.strokeWidth = Number(val.store.data.attrs.body.strokeWidth);
            this.drawerNode.stroke = val.store.data.attrs.body.stroke;
            this.drawerNode.nodeType = val.store.data.attrs.nodeData.type;
            const flowNode = val.store.data.attrs.nodeData.flowNode;
            this.drawerNode.entityId = flowNode.entityId;
            this.drawerNode.itemId = flowNode.itemId;
            this.drawerNode.flowNodeType = flowNode.flowNodeType;
            this.drawerNode.groupIdentify = flowNode.groupIdentify;
            this.drawerNode.childFlowIdentify = flowNode.childFlowIdentify;
            this.drawerNode.methodExp = flowNode.methodExp;
            this.drawerNode.methodParams = flowNode.methodParams;
            this.drawerNode.methodType = flowNode.methodType;
            this.drawerNode.flowJudges = flowNode.flowJudges;
            // this.drawerNode.isJudgeNode = flowNode.isJudgeNode;
            //方法
            if (this.drawerNode.methodName != flowNode.methodName) {
              this.drawerNode.methodName = flowNode.methodName;
              //之后重新发请求获取参数数据
            } else {
              //方法名称相同时
              this.methodParams.forEach(item => {
                item.className = '';
                const methodParams = this.drawerNode.methodParams ? JSON.parse(this.drawerNode.methodParams) : [];
                for (let i = 0; i < methodParams.length; i++) {
                  if (methodParams[i].name === item.name) {
                    item.className = methodParams[i].className;
                    break;
                  }
                }
              })
            }
          } else { //边
            this.drawerEdge.edgeText = val.store.data.labels ? val.store.data.labels[0].text != undefined ? val.store.data.labels[0].text : val.store.data.labels[0].attrs.label.text : '';
            this.drawerEdge.edgeWidth = Number(val.store.data.attrs.line.strokeWidth);
            this.drawerEdge.edgeColor = val.store.data.attrs.line.stroke;
            //处理条件连线
            let sourceNode = this.graph.getCellById(val.store.data.source.cell);
            // console.log(sourceNode, val)
            //判断源节点是否为条件节点
            if (sourceNode.store.data.attrs.nodeData.type === 'polygon') {
              this.drawerEdge.isCondition = true;
              if (this.drawerEdge.edgeText === '') {
                this.drawerEdge.edgeText = this.drawerEdge.edgeSelect ? '是' : '否';
                //修改线条文本
                this.changeEdgeText();
              }
              this.drawerEdge.edgeSelect = this.drawerEdge.edgeText === '是' ? true : false;
            } else {
              this.drawerEdge.isCondition = false;
            }
          }
        }
      },
      immediate: true,
      deep: false
    },
    //监听方法变化
    'drawerNode.methodName'(val) {
      // 方法切换
      if (this.selectCell.store.data.attrs.nodeData.flowNode.methodName !== val) {
        console.log('方法名称改变了')
        //移除参数数据
        this.clearParams();
      }
      this.methodParams = [];
      for (let i = 0, len = this.codeMethods.length; i < len; i++) {
        if (this.codeMethods[i].name === val) {
          this.selectM(this.codeMethods[i]);
          break;
        }
      }
    },
    //监听循环实体变化
    'drawerNode.entityId'(val) {
      //实体类属性
      this.entityItemInfos = [];
      for (let i = 0, len = this.curEntityList.length; i < len; i++) {
        if (this.curEntityList[i].entityId === val) {
          this.getEntityProperties(this.curEntityList[i]);
          break;
        }
      }
    },
    //监听条件连线判断变化
    'drawerEdge.edgeSelect'(val) {
      this.drawerEdge.edgeText = val ? '是' : '否';
    }
  },
  methods: {
    // 网格设置
    changeGridStatus() {
      this.grid.showGrid ? this.graph.showGrid() : this.graph.hideGrid();
    },
    changeGridType(e) {
      this.grid.type = e;
      this.changeGrid();
    },
    changeGrid() {
      this.graph.drawGrid({
        ...this.grid
      })
    },
    // 节点设置
    changeStrokeWidth(val) {
      this.selectCell.attr('body/strokeWidth', val);
    },
    changefontSize(val) {
      this.selectCell.attr('label/fontSize', val);
    },
    changeNodeText() {
      this.selectCell.attr('label/text', this.drawerNode.nodeText);
    },
    changeStroke(val) {
      this.drawerNode.stroke = val;
      this.selectCell.attr('body/stroke', this.drawerNode.stroke)
    },
    changeFontFill(val) {
      this.drawerNode.fontFill = val;
      this.selectCell.attr('label/fill', this.drawerNode.fontFill);
    },
    changeFill(val) {
      this.drawerNode.fill = val;
      this.selectCell.attr('body/fill', val);
    },
    // 边设置
    changeEdgeText() {
      // console.log(this.drawerEdge.edgeText);
      this.selectCell.setLabels(
        [{ attrs: { label: { text: this.drawerEdge.edgeText } } }]
      )
    },
    changeEdgeWidth(val) {
      this.drawerEdge.edgeWidth = val;
      this.selectCell.attr('line/strokeWidth', this.drawerEdge.edgeWidth);
    },
    changeEdgeColor(val) {
      this.drawerEdge.stroke = val;
      this.selectCell.attr('line/stroke', this.drawerEdge.stroke);
    },
    // node节点自定义参数设置
    changeFlowNode(val, key) {
      this.selectCell.attr('nodeData/flowNode/' + key, val);
    },
    // 移除方法下的参数
    clearParams() {
      this.changeFlowNode('', 'methodParams');
      this.changeFlowNode('', 'methodExp');
      this.methodParams.forEach(item => {
        item.className = '';
      })
    },
    /**
     * 检查方法method
    */
    checkMethodForm() {
      let inputValue = this.drawerNode.methodName;
      if (this.showParams && this.methodParams) {
        for (let i = 0; i < this.methodParams.length; i++) {
          let item = this.methodParams[i];
          let value = item.className;
          if (!value) {
            this.$message.error('请输入' + item.desc);
            return false;
          }
          if (item.type === 'int') {
            const digit = /^[0-9]*$/;
            if (!digit.test(value)) {
              this.$message.error(item.desc + '只能输入数字');
              return false;
            }
          } else if (item.type === 'String') {
            value = '"' + value + '"';
          }
          let p = '$' + item.name + '$';
          inputValue = inputValue.replace(p, value);
        }
        this.changeFlowNode(JSON.stringify(this.methodParams), 'methodParams');
        this.changeFlowNode('MethodUtil.' + inputValue, 'methodExp');
        this.$message.success('方法节点参数数据写入成功');
        return true;
      } else {
        //移除参数
        this.clearParams();
        return true;
      }
    },
    //保存编辑条件
    saveflowJudges() {
      let v = true;
      // let bv = true;
      //校验条件
      for (let i = 0; i < this.$refs['conditionEdit'].flowJudges.length; i++) {
        // console.log(this.$refs['conditionEdit'].$refs)
        this.$refs['conditionEdit'].$refs['conditionForm'][i].validate(valid => {
          v = valid;
        });
      }
      if (!v) {
        return;
      }
      //校验否判断直接返回
      // this.$refs['conditionEdit'].$refs['conditionBackForm'].validate(valid => {
      //   bv = valid;
      // });
      //全部校验通过才允许修改
      if (v) {
        this.selectCell.attr('nodeData/flowNode/flowJudges', this.$refs['conditionEdit'].flowJudges);
        // this.selectCell.attr('nodeData/flowNode/isJudgeNode', this.$refs['conditionEdit'].backForm.isJudgeNode);
        this.dialogVisible = false;
      }
    },
    // 置顶
    toTopZIndex() {
      this.selectCell.toFront();
    },
    // 删除
    deleteNode() {
      this.$emit('deleteNode');
    },
    //编辑节点条件
    showConditionEdit() {
      this.dialogVisible = true;
      //条件
      this.$nextTick(() => {
        const conditionEdit = this.$refs['conditionEdit'];
        conditionEdit.flowJudges = JSON.parse(JSON.stringify(this.drawerNode.flowJudges));
        // 刷新下拉框数据
        conditionEdit.update();
        // conditionEdit.backForm.isJudgeNode = JSON.parse(JSON.stringify(this.drawerNode.isJudgeNode));
      })

    },
    // 选择方法
    selectM(data) {
      // this.flow.methodName = data.name;
      // this.flow.flowShapeName = data.className;
      this.showParams = false;
      // 有参数
      if (data.type === '1' || data.type === '3') {
        if (data.params) {
          this.showParams = true;
          let params = data.params;
          params.forEach(item => {
            // item.className = this.methodParams[item.name] || '';
            item.className = '';
            const methodParams = this.drawerNode.methodParams ? JSON.parse(this.drawerNode.methodParams) : [];
            for (let i = 0; i < methodParams.length; i++) {
              if (methodParams[i].name === item.name) {
                item.className = methodParams[i].className;
                break;
              }
            }
          })
          this.methodParams = params;
          this.changeFlowNode(true, 'hasMethodParams');
        }
        this.changeFlowNode(false, 'hasMethodParams');
      }
      if (data.type === '0' || data.type === '1' || data.type === '2') {
        this.drawerNode.methodType = '0';
      } else {
        this.drawerNode.methodType = '1';
      }
      this.changeFlowNode(this.drawerNode.methodType, 'methodType');
    },
    // 获取实体类的属性
    getEntityProperties(item) {
      let params = {
        id: item.entityId + ''
      };
      // 获取实体类属性
      this.entityItemInfos = [];
      entityItemList(params).then(res => {
        if (res.data.data) {
          res.data.data.forEach(item => {
            if (item.itemType === 'List') {
              item['label'] = item.itemName + '--' + item.itemIdentify;
              this.entityItemInfos.push(item);
            }
          });
        }
      });
    },
    // 获取规则组信息
    getGroupList(ids) {
      let params = {
        ids: JSON.stringify(ids),
        taskNo: this.$route.params.taskNo || this.$route.params.rowTaskNo
      };
      listGroupInfosByEntity(params).then((res) => {
        this.groupList = res.data.data;
      });
    },
    // 获取子流程信息
    getFlowList(ids) {
      let params = {
        ids: JSON.stringify(ids),
      };
      listFlowInfosByEntity(params).then(res => {
        this.flows = res.data.data;
      });
    },
    // 展开抽屉
    toggleDrawer() {
      this.drawerHide = !this.drawerHide;
      this.$refs['drawerContainer'].style.right = this.drawerHide ? '-300px' : '0px';
    },
    //获取方法
    initMethods() {
      getMethodName({}).then((res) => {
        this.codeMethods = res.data.data;
      });
    },
    init() {
      //当前规则组
      this.getGroupList(this.checkEntity);
      this.getFlowList(this.checkEntity);
      this.initMethods();
    }
  }
};
</script>

<style lang="less" scoped>
@bd-color: #e8eaec;

.drawer-container {
  position: relative;
  max-width: 300px;
  min-width: 300px;
  border: 1px solid @bd-color;
  // overflow: hidden;

  .drawer-map {
    border-bottom: 1px solid @bd-color;
  }

  .drawer-title {
    border-bottom: 1px solid @bd-color;
    box-sizing: border-box;
    padding: 14px 10px;
    color: #333;
    font-size: 16px;
  }

  .drawer-wrap {
    box-sizing: border-box;
    padding: 10px 20px 10px 10px;
    overflow: auto;
  }

  .drawer-unfold {
    position: absolute;
    top: 40%;
    left: -20px;
    width: 20px;
    height: 40px;
    line-height: 40px;
    font-size: 12px;
    text-align: center;
    background-color: #848181;
    color: #ffffff;
    border-top-left-radius: 10px;
    border-bottom-left-radius: 10px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      color: #333333;
      background-color: #ececec;
    }

    i {
      transform: scale(0.7);
    }
  }
}
</style>
